<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Visual Basic Arrays</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Visual Basic, learn Visual Basic, arrays, tutorial, programming language">
<meta name="description" content="This part of the Visual Basic tutorial covers Arrays in Visual Basic.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Arrays</h1>

<p>
In this part of the Visual Basic programming tutorial, we will cover arrays. 
We will initiate arrays and read data from them.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>

<p>
<b>Arrays</b> are collections of data. A variable can hold only one item at a time. 
Arrays can hold multiple items. These items are called elements of the array.
Arrays store data of the <b>same data type</b>. Each element can be referred
to by an index. Arrays are zero based. The index of the first element is zero.
</p>

<p>
<b>Collections</b> serve the
similar purpose. They are are more powerful than arrays. They will be described later.
</p>


<p>
Arrays are used to store data of our applications.
We declare arrays to be of a certain data type. We specify their
length. And we initialize arrays with data. We have several
methods for working with array. We can modify the elements, sort
them, copy them or search them.
</p>


<h2>Initializing arrays</h2>

<p>
There are several ways, how we can initialize an array in Visual Basic. 
</p>


<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim array(5) As Integer

        array(0) = 3
        array(1) = 2
        array(2) = 1
        array(3) = 5
        array(4) = 6

        For i As Integer = 0 To array.Length-1
            Console.WriteLine(array(i))
        Next

    End Sub

End Module
</pre>

<p>
We declare and initialize a numerical array. The contents of the
array are printed to the console. 
</p>

<pre class="explanation">
Dim array(5) As Integer
</pre>

<p>
Here we declare an array which contains five elements. All elements
are integers. 
</p>

<pre class="explanation">
array(0) = 3
array(1) = 2
...
</pre>

<p>
We initialize the array with some data. This is assignment initialization. 
The indexes are in the parentheses. Number 3 is going to be
the first element of the array, 2 the second. 
</p>

<pre class="explanation">
For i As Integer = 0 To array.Length-1
    Console.WriteLine(array(i))
Next
</pre>

<p>
We go through the array and print its elements. An array has a 
<code>Length</code> property, which gives the number of elements
in the array. Since arrays are zero based, the indexes are 0..length-1.
</p>

<hr class="btm">

<p>
We can declare and initialize an array in one statement.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim array() As Integer = { _
            2, 4, 5, 6, 7, 3, 2 }

        For Each i As Integer In array
            Console.WriteLine(i)
        Next

    End Sub

End Module
</pre>

<p>
This is a modified version of the previous program.
</p>

<pre class="explanation">
Dim array() As Integer = { _
    2, 4, 5, 6, 7, 3, 2 }
</pre>

<p>
An array is declared and initialized in one step. The elements
are specified in the curly brackets. We did not specify the length
of the array. The compiler will do it for us. 
</p>

<pre class="explanation">
For Each i As Integer In array
    Console.WriteLine(i)
Next
</pre>

<p>
We use the <code>For Each</code> keyword to traverse the array
and print its contents.
</p>

<h2>The bounds of an array</h2>


<p>
Visual Basic has two functions for getting the bounds of an array.
The <code>LBound()</code> function returns the lowest 
available subscript for the indicated dimension of an array.
The <code>UBound()</code> function returns the highest
available subscript for the indicated dimension of an array.
So far we have worked with one dimensional arrays. 
</p>

<pre class="code">
Option Strict On

Module Example

    Dim n1 As Integer
    Dim n2 As Integer

    Sub Main()
        
        Dim names() As String = { "Jane", "Lucy", _
            "Timea", "Beky", "Lenka"}

        n1 = LBound(names)
        n2 = UBound(names)

        Console.WriteLine(n1)
        Console.WriteLine(n2)

        For i As Integer = n1 To n2
            Console.WriteLine(names(i))
        Next

    End Sub

End Module
</pre>

<p>
We have an array of names. We calculate and work with the
lower and upper bound of that array.
</p>

<pre class="explanation">
n1 = LBound(names)
n2 = UBound(names)
</pre>

<p>
n1 is the lowest index, n2 the highest index in the names array.
</p>

<pre class="explanation">
For i As Integer = n1 To n2
    Console.WriteLine(names(i))
Next
</pre>

<p>
We examine the array using both the lower and upper bounds
of the array.
</p>

<pre>
$ ./bounds.exe 
0
4
Jane
Lucy
Timea
Beky
Lenka
</pre>

<p>
Output of the example.
</p>

<h2>Array dimensions</h2>

<p>
So far, we have worked with one dimensional arrays. The number of indexes needed to 
specify an element is called the <b>dimension</b>, or <b>rank</b> of the array.
</p>

<p>
We will work with two dimensional array.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim numbers(,) As Integer = { {2, 1}, {3, 5}, _
            {4, 4}, {7, 2}, {0, 0} }

        For i As Integer = 0 To UBound(numbers, 1)
            For j As Integer = 0 To UBound(numbers, 2)
                Console.Write(CStr(numbers(i, j)) + " ")
            Next j
            Console.Write(vbNewLine)
        Next i

    End Sub

End Module
</pre>

<p>
If we need two indexes to access an element in an array, than
we have a two dimensional array. 
</p>


<pre class="explanation">
Dim numbers(,) As Integer = { {2, 1}, {3, 5}, _
    {4, 4}, {7, 2}, {0, 0} }
</pre>

<p>
We declare and initialize a two dimensional array in one statement. Note the
comma inside the parentheses following the name of the array. 
</p>

<pre class="explanation">
For i As Integer = 0 To UBound(numbers, 1)
    For j As Integer = 0 To UBound(numbers, 2)
        Console.Write(CStr(numbers(i, j)) + " ")
    Next j
    Console.Write(vbNewLine)
Next i
</pre>

<p>
We need two loops to get the data from the two dimensional array.
The <code>UBound()</code> function has an optional second
parameter, rank. It is a dimension for which we retrieve the highest
index. If the rank is omitted, that 1 dimension is assumed. 
</p>

<pre>
$ ./twodimensions.exe 
2 1 
3 5 
4 4 
7 2 
0 0 
</pre>

<p>
Output of the code example. 
</p>

<hr class="btm">

<p>
Next we will work with a three dimensional array.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim i As Integer
        Dim j As Integer
        Dim k As Integer

        Dim nums(,,) As Integer = { _
            {{12, 2, 8}}, _
            {{14, 5, 2}}, _
            {{3, 26, 9}}, _
            {{4, 11, 2}} _
        }

        For i = 0 To UBound(nums, 1)
            For j = 0 To UBound(nums, 2)
                For k = 0 To UBound(nums, 3) 
                    Console.Write(CStr(nums(i, j, k)) + " ")
                Next k
            Next j     
            Console.Write(vbNewLine)       
        Next i

    End Sub

End Module
</pre>

<p>
We have a numerical three dimensional array. Again, we initialize
the array with numbers and print them to the terminal. 
</p>

<pre class="explanation">
Dim nums(,,) As Integer = { _
    {{12, 2, 8}}, _
    {{14, 5, 2}}, _
    {{3, 26, 9}}, _
    {{4, 11, 2}} _
}
</pre>

<p>
There is another comma between the parentheses on the left side 
and additional curly brackets on the right side. 
</p>

<pre class="explanation">
For k = 0 To UBound(nums, 3) 
    Console.Write(CStr(nums(i, j, k)) + " ")
Next k
</pre>

<p>
This loop goes through the third dimension. We use three indexes to
retrieve the value from the array. 
</p>

<pre>
$ ./3darray.exe 
12 2 8 
14 5 2 
3 26 9 
4 11 2 
</pre>

<p>
We print the contents of the three dimensional array to the
console. 
</p>

<hr class="btm">

<p>
There is a <code>Rank()</code> function, which gives
the number of dimensions of an array.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim array1() As Integer = {1, 2}
        Dim array2(,) As Integer = { { 1 }, { 2 } }
        Dim array3(, ,) As Integer = { { { 1, 2 }, { 2, 1 } } } 

        Console.WriteLine(array1.Rank())
        Console.WriteLine(array2.Rank())
        Console.WriteLine(array3.Rank())

    End Sub

End Module
</pre>

<p>
We have three arrays. We use the <code>Rank()</code> function
to get the number of dimensions for each of them. 
</p>

<pre class="explanation">
Console.WriteLine(array1.Rank())
</pre>

<p>
Here we get the rank for the first array.
</p>



<h2>Jagged arrays</h2>

<p>
Arrays that have elements of the same size are called <b>rectangular</b> arrays.
In contrast, arrays which have elements of different size are called 
<b>jagged</b> arrays. Jagged arrays are declared and initialized differently.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
    
        Dim jagged As Integer()() = New Integer(4)() {}

        jagged(0) = New Integer() {1}
        jagged(1) = New Integer() {3, 4}
        jagged(2) = New Integer() {5, 6, 7}
        jagged(3) = New Integer() {5, 6}
        jagged(4) = New Integer() {9}


        For i As Integer = 0 To jagged.GetUpperBound(0)
            For j As Integer = 0 To jagged(i).GetUpperBound(0)
                Console.Write(jagged(i)(j) &amp; " ")
            Next

            Console.Write(vbNewLine)
        Next

    End Sub

End Module
</pre>

<p>
This is an example of a jagged array. 
</p>

<pre class="explanation">
Dim jagged As Integer()() = New Integer(4)() {}
</pre>

<p>
This is a declaration of a jagged array. We have
an array of arrays. More specifically, we have declared
an array to have five arrays of Integer data type. 
</p>

<pre class="explanation">
jagged(0) = New Integer() {1}
jagged(1) = New Integer() {3, 4}
...
</pre>

<p>
Each of the arrays must be individually initialized. 
</p>

<pre class="explanation">
Console.Write(jagged(i)(j) &amp; " ")
</pre>

<p>
Unlike in rectangular arrays, each index is surrounded by 
parentheses.
</p>

<h2>Array methods</h2>

<p>
There are various methods for working with arrays. 
These methods can be used for retrieving, modifying
data, sorting, copying, searching data. These methods that
we use are static methods of the Array class or member methods
of the array objects. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim names() As String = {"Jane", "Frank", "Alice", "Tom" }

        Array.Sort(names)

        For Each el As String In names
            Console.Write(el + " ")
        Next

        Console.Write(vbNewLine)

        Array.Reverse(names)

        For Each el As String In names
            Console.Write(el + " ")
        Next

        Console.Write(vbNewLine)

    End Sub

End Module
</pre>

<p>
In this example, we sort the data. 
</p>

<pre class="explanation">
Dim names() As String = {"Jane", "Frank", "Alice", "Tom" }
</pre>

<p>
We have an array of strings. 
</p>

<pre class="explanation">
Array.Sort(names)
</pre>

<p>
The <code>Sort()</code> method sorts the data alphabetically.
</p>

<pre class="explanation">
Array.Reverse(names)
</pre>

<p>
The <code>Reverse()</code> method reverses the sequence of 
the elements in the entire one-dimensional array.
</p>

<pre>
$ ./sorting.exe 
Alice Frank Jane Tom 
Tom Jane Frank Alice
</pre>

<p>
We have ordered the names in ascending and descending order. 
</p>

<hr class="btm">

<p>
The following example uses <code>SeValue()</code>,
<code>GetValue()</code>, <code>IndexOf()</code>, 
<code>Copy()</code> and <code>Clear()</code> methods.
</p>

<pre class="code">
Option Strict On

Module Example

    Dim names() As String = {"Jane", "Frank", "Alice", "Tom" }
    Dim girls(0 To 3) As String

    Sub Main()

        names.SetValue("Beky", 1)
        names.SetValue("Erzebeth", 3)

        Console.WriteLine(names.GetValue(1))
        Console.WriteLine(names.GetValue(3))

        Console.WriteLine(Array.IndexOf(names, "Erzebeth"))

        Array.Copy(names, girls, names.Length)

        For Each el As String In girls
            Console.Write(el + " ")
        Next         

        Console.Write(vbNewLine)

        Array.Clear(names, 0, 2)

        For Each el As String In names
            Console.Write(el + " ")
        Next

        Console.Write(vbNewLine)

    End Sub

End Module
</pre>

<p>
This example introduces additional methods. 
</p>

<pre class="explanation">
Dim girls(0 To 3) As String
</pre>

<p>
Yet another way to declare an array.
</p>

<pre class="explanation">
names.SetValue("Beky", 1)
names.SetValue("Erzebeth", 3)
</pre>

<p>
The <code>SetValue()</code> sets a value for a 
specific index in the array. 
</p>

<pre class="explanation">
Console.WriteLine(names.GetValue(1))
Console.WriteLine(names.GetValue(3))
</pre>

<p>
We retrieve the values from the array with the 
<code>GetValue()</code> method.
</p>

<pre class="explanation">
Console.WriteLine(Array.IndexOf(names, "Erzebeth"))
</pre>

<p>
The <code>IndexOf()</code> method returns an index
for the first occurrence of a specific value. 
</p>

<pre class="explanation">
Array.Copy(names, girls, names.Length)
</pre>

<p>
The <code>Copy()</code> method copies values
from the source array to the destination array. The first parameter
is the source array, the second is the destination array. The third
parameter is the length; it specifies the number of elements to copy.
</p>

<pre class="explanation">
Array.Clear(names, 0, 2)
</pre>

<p>
The <code>Clear()</code> method clears elements from the array.
It takes three parameters, the array, the start index and the number 
of elements from the index to clear.
</p>


<p>
In this part of the Visual Basic tutorial, we worked with arrays. 
We described various types of arrays and methods to work with them.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 1, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

